<?php

class Model_Forum_Message extends Forum_Db_Table
{
	protected $_name = 'forum_message';
    
    protected $_primary = 'id';
	
    /**
     * Get list of messages
     * 
     * @return array
     */
    public function getList($mode = 'approved'){
        $query = "SELECT fm.*, ft.title AS thread
            FROM {$this->_name} AS fm
            LEFT JOIN forum_thread AS ft ON ft.id = fm.thread_id";

        if ($mode != 'all') {
            $query .= " WHERE fm.status = '{$mode}'";
        }
        
        $query .= " ORDER BY fm.created_on DESC";
        
        return $this->getAdapter()->fetchAll($query);
    }
    
	public function getListCountInForum(){
        $query = "SELECT DISTINCT forum_id , count(*) as `count`
                  FROM {$this->_name}, forum_thread
				  WHERE forum_thread.status = 'approved' AND
				  		{$this->_name}.status = 'approved' AND
						forum_thread.id = {$this->_name}.thread_id
				  GROUP BY forum_id";

        return $this->getAdapter()->fetchAll($query);		
	}
	
	public function getListCountInForumById($arrayForumId){
		if( !is_array($arrayForumId) ){ return false; }
		
		$listArr = implode(", ", $arrayForumId);
        
		$query = "SELECT DISTINCT forum_id , count(*) as `count`
                  FROM {$this->_name}, forum_thread
				  WHERE forum_thread.status = 'approved' AND
				  		{$this->_name}.status = 'approved' AND
				    	forum_thread.id = {$this->_name}.thread_id AND
				  		forum_id in ({$listArr})
				  GROUP BY forum_id";

        return $this->getAdapter()->fetchAll($query);		
	}

	public function getListCountInThreadById($arrayThreadId){
		if( !is_array($arrayThreadId) ){ return false; }
		
		$listArr = implode(", ", $arrayThreadId);
        $query = "SELECT thread_id , count(*) as `count`
                  FROM {$this->_name}
				  WHERE {$this->_name}.status = 'approved' AND thread_id in ({$listArr})
				  GROUP BY thread_id";

        return $this->getAdapter()->fetchAll($query);		
	}

	public function getListLastInForum(){
        $query = "SELECT fs.forum_id, fm.thread_id, fm.user_id, UNIX_TIMESTAMP(fm.created_on) as `date`
                  FROM forum_message AS fm, forum_thread AS fs
				  WHERE fm.thread_id = fs.id 
				        AND fs.status = 'approved' 
				  		AND fm.status = 'approved'
				  		AND fm.created_on = (SELECT max(fm2.created_on)
											 FROM forum_message AS fm2, forum_thread AS fs2
											 WHERE fs.forum_id= fs2.forum_id
											 	   AND fm2.thread_id = fs2.id
												   AND fs2.status = 'approved' 
				  								   AND fm2.status = 'approved'
											 GROUP BY fs.forum_id)
				  GROUP BY fs.forum_id";

        return $this->getAdapter()->fetchAll($query);		
	}	

	public function getListLastInForumById($arrayForumId){
		if( !is_array($arrayForumId) ){ return false; }
		
		$listArr = implode(", ", $arrayForumId);
        $query = "SELECT fs.forum_id, fm.thread_id, fm.user_id, UNIX_TIMESTAMP(fm.created_on) as `date`
                  FROM forum_message AS fm, forum_thread AS fs
				  WHERE fs.forum_id in ({$listArr})
				  		AND fm.thread_id = fs.id
						AND fs.status = 'approved' 
				  		AND fm.status = 'approved'
				  		AND fm.created_on = (SELECT max(fm2.created_on)
											 FROM forum_message AS fm2, forum_thread AS fs2
											 WHERE fs.forum_id= fs2.forum_id
											 	   AND fm2.thread_id = fs2.id
												   AND fs2.status = 'approved' 
				  								   AND fm2.status = 'approved'
												   AND fs2.forum_id in ({$listArr})
											 GROUP BY fs.forum_id)
				  GROUP BY fs.forum_id";
        return $this->getAdapter()->fetchAll($query);		
	}	

	public function getListLastInThreadById($arrayThreadId){
		if( !is_array($arrayThreadId) ){ return false; }
		
		$listArr = implode(", ", $arrayThreadId);
        $query = "SELECT thread_id, user_id, UNIX_TIMESTAMP(created_on) AS `date`
				  FROM forum_message AS f1
                  WHERE thread_id in ({$listArr})
				  		AND f1.status = 'approved'
				  		AND created_on = (SELECT  max(created_on)
				                          FROM forum_message AS f2
										  WHERE f1.thread_id= f2.thread_id
										  		AND f2.status = 'approved'
										  GROUP BY thread_id)
				  GROUP BY thread_id";

        return $this->getAdapter()->fetchAll($query);		
	}
    
	public function getPageByThreadId($thread_id, $page, $resOnPage = 10){
		if(isset($thread_id) && isset($page) && isset($resOnPage)){
			$from = $page*$resOnPage - $resOnPage;
			
	        $query = "SELECT *, UNIX_TIMESTAMP(created_on) as created_on
	            FROM {$this->_name}
	            WHERE thread_id = {$thread_id}
						AND status = 'approved'
				ORDER BY created_on
				LIMIT {$from},{$resOnPage}";
				
	        $res['list'] = $this->getAdapter()->fetchAll($query);

	        $query = "SELECT count(*)
	            FROM {$this->_name}
	            WHERE thread_id = {$thread_id}
						AND status = 'approved'
				ORDER BY created_on";
				
	        $res['total'] = $this->getAdapter()->fetchOne($query);		
			
			return $res;	
						
		}

	}
    /**
     * Updates message row according to $bind param
     * 
     * @param mixed $ids
     * @param array $bind Column => Value pairs
     * @return bool
     */
	
    public function update($ids, $bind)
    {
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        
        $count = count($ids);
        $ids = implode(',', $ids);
        
        if ($this->getAdapter()->update($this->_name, $bind, array("id IN ({$ids})"))) {
            Forum_Message::getInstance()->addSuccess(sprintf('%d %s успішно оновлено', $count, (
                $count > 4 ? 'повідомлень' : (
                    $count > 1 ? 'повідомлення' : 'повідомлення' //this is wrong, and i know this :/
                )
            )));
            return true;
        } else {
            Forum_Message::getInstance()->addError('Записи не були оновлені. Спробуйте ще раз');
            return false;
        }
    }
    
    /**
     * Delete message rows by ids
     * 
     * @param mixed $id
     * @return bool
     */
    public function delete($ids)
    {
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        
        $count = count($ids);
        $ids = implode(',', $ids);
        
        if ($this->getAdapter()->delete($this->_name, "id IN ({$ids})")) {
            Forum_Message::getInstance()->addSuccess(sprintf('%d %s успішно видалено', $count, (
                $count > 4 ? 'повідомлень' : (
                    $count > 1 ? 'повідомлення' : 'повідомлення' //this is wrong, and i know this :/
                )
            )));
            return true;
        } else {
            Forum_Message::getInstance()->addError('Записи не були видалені. Спробуйте ще раз');
            return false;
        }
    }
	
	public function add($mass){
		if(is_array($mass)){
			$error = false;
			if(!isset($mass['title']) || empty($mass['title'])){
				Forum_Message::getInstance()->addError("Вкажіть заголовок повідомлення");
				$error = true;
			}
			if(!isset($mass['content']) || empty($mass['content'])){
				Forum_Message::getInstance()->addError("Додайте текст повідомленя");
				$error = true;
			}
			if(!isset($mass['thread_id']) || empty($mass['thread_id'])){
				Forum_Message::getInstance()->addError("Не потрібно хитрувати");
				$error = true;
			}
			if($error){
				return false;
			}else{
				if(Model_User::getUserId()){
					$mass['user_id'] = Model_User::getUserId();
				}
				$mass['created_on'] = date('Y-m-d H:i:s');;
				if($this->getAdapter()->insert($this->_name, $mass)){
					Forum_Message::getInstance()->addSuccess("Ваше повідомлення додано");
					return true;
				}else{
					Forum_Message::getInstance()->addError("Помилка при додаванні повідомлення");
					return false;
				}
			}
			return false;
		}

	}
}

?>